//
//  MainViewController.m
//  Shanghai Cuisine
//
//  Created by iOS Two on 14-9-10.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "MainViewController.h"
#import "UIImageView+MJWebCache.h"
#import "DetailViewController.h"
#import "NSTimer+Addition.h"
#import "FavoriteViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if (version >= 7) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    } else {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_navbackbule4"] forBarMetrics:UIBarMetricsDefault];
    }
    [MobClick endLogPageView:@"MainViewController"];

}
-(void)viewWillAppear:(BOOL)animated {
    if (version >= 7) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    } else {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_navbackpuple4"] forBarMetrics:UIBarMetricsDefault];
    }
    [MobClick beginLogPageView:@"MainViewController"];
//    [_mainScorllView.animationTimer resumeTimer];
}
-(void)viewDidDisappear:(BOOL)animated {
//    [_mainScorllView.animationTimer pauseTimer];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (version >= 7) { // 判断是否是IOS7
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    }
    
    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:nil];

    UIBarButtonItem* backBtn = [[UIBarButtonItem alloc]init];
    backBtn.title = @"返回";
    self.navigationItem.backBarButtonItem = backBtn;
    
    _nameArray = [[NSMutableArray alloc]init];
    _imgArray = [[NSMutableArray alloc]init];
    _bigImg = [[NSMutableArray alloc]init];
    _materialArray = [[NSMutableArray alloc]init];
    _materialQuantity = [[NSMutableArray alloc]init];
    _dishId = [[NSMutableArray alloc]init];
    _tips = [[NSMutableArray alloc]init];
    _auxiliaryMaterial = [[NSMutableArray alloc]init];
    _auxiliaryQuantity = [[NSMutableArray alloc]init];
    _introductionArray = [[NSMutableArray alloc]init];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
    titleLabel.text = @"本帮菜";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:24];
    titleLabel.textColor = [UIColor colorWithRed:0.97 green:0.69 blue:0.17 alpha:1];

    self.navigationItem.titleView = titleLabel;
    [self creatController];
    [self getData];
    // Do any additional setup after loading the view.
}
-(void)downloadImage:(NSString *)url {
    _hotId = [[NSMutableArray alloc]init];
    _hotImg = [[NSMutableArray alloc]init];
    _hotName = [[NSMutableArray alloc]init];
    _hotTips = [[NSMutableArray alloc]init];
    _hotBigImg = [[NSMutableArray alloc]init];
    _hotMaterialArray = [[NSMutableArray alloc]init];
    _hotMaterialQuantity = [[NSMutableArray alloc]init];
    _hotAuxiliaryMaterial = [[NSMutableArray alloc]init];
    _hotAuxiliaryQuantity = [[NSMutableArray alloc]init];
    _hotIntroductionArray = [[NSMutableArray alloc]init];
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"dishName"];
    [query whereKey:@"isHot" equalTo:[NSNumber numberWithBool:YES]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (int i = 0; i < objects.count; i++) {
            [_hotName addObject:[[objects objectAtIndex:i] objectForKey:@"dishName"]];
            [_hotImg addObject:[[objects objectAtIndex:i] objectForKey:@"bannerImg"]];
            [_hotBigImg addObject:[[objects objectAtIndex:i] objectForKey:@"bigImg"]];
            [_hotMaterialArray addObject:[[objects objectAtIndex:i] objectForKey:@"material"]];
            [_hotMaterialQuantity addObject:[[objects objectAtIndex:i] objectForKey:@"materialQuantity"]];
            [_hotId addObject:[[objects objectAtIndex:i] objectForKey:@"objectId"]];
            [_hotTips addObject:[[objects objectAtIndex:i] objectForKey:@"tips"]];
            [_hotAuxiliaryQuantity addObject:[[objects objectAtIndex:i] objectForKey:@"auxiliaryQuantity"]];
            [_hotAuxiliaryMaterial addObject:[[objects objectAtIndex:i] objectForKey:@"auxiliaryMaterial"]];
            [_hotIntroductionArray addObject:[[objects objectAtIndex:i] objectForKey:@"introduction"]];
        }
        [self performSelectorOnMainThread:@selector(updataUI) withObject:nil waitUntilDone:YES];
    }];
}
-(void)updataUI {
    NSMutableArray *viewsArray = [[NSMutableArray alloc]init];
    for (int i = 0; i < 3; i++) {
        UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 158)];
        
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 158)];
        if (_hotImg.count != 0) {
            [image setImageURLStr:[_hotImg objectAtIndex:i] placeholder:[UIImage imageNamed:@"img_newdish"]];
            
        }
        [back addSubview:image];
        
        [viewsArray addObject:back];
    }
    [_mainTable reloadData];
    _mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 158) animationDuration:3];
    _mainScorllView.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];
    _mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    _mainScorllView.totalPagesCount = ^NSInteger(void){
        return 3;
    };
    _mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
        [MobClick event:@"clickAdvTimes"];
        [self clickAdv:pageIndex];
        NSLog(@"点击了第%d个",pageIndex);
    };
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(254, 20, 66, 27);
    [button addTarget:self action:@selector(goTo) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"img_favor"] forState:UIControlStateNormal];
    [_mainScorllView addSubview:button];
    
    _mainTable.tableHeaderView = _mainScorllView;
}
-(void)creatController {
    _mainTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, kHeight - 64) style:UITableViewStylePlain];
    _mainTable.delegate = self;
    _mainTable.dataSource = self;
    _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_mainTable];
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 7)];
    image.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    _mainTable.tableFooterView = image;
}
-(void)getData {
    [self showIndeterminateProgress];
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"dishName"];
    query.cachePolicy = kPFCachePolicyNetworkElseCache;
    query.maxCacheAge = 24 * 3600 * 30;//缓存时间有效期
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (int i = 0; i < objects.count; i++) {
            [_nameArray addObject:[[objects objectAtIndex:i] objectForKey:@"dishName"]];
            [_imgArray addObject:[[objects objectAtIndex:i] objectForKey:@"imgUrl"]];
            [_bigImg addObject:[[objects objectAtIndex:i] objectForKey:@"bigImg"]];
            [_materialArray addObject:[[objects objectAtIndex:i] objectForKey:@"material"]];
            [_materialQuantity addObject:[[objects objectAtIndex:i] objectForKey:@"materialQuantity"]];
            [_dishId addObject:[[objects objectAtIndex:i] objectForKey:@"objectId"]];
            [_tips addObject:[[objects objectAtIndex:i] objectForKey:@"tips"]];
            [_auxiliaryQuantity addObject:[[objects objectAtIndex:i] objectForKey:@"auxiliaryQuantity"]];
            [_auxiliaryMaterial addObject:[[objects objectAtIndex:i] objectForKey:@"auxiliaryMaterial"]];
            [_introductionArray addObject:[[objects objectAtIndex:i] objectForKey:@"introduction"]];
        }
        [HUD hide:YES];
        [_mainTable reloadData];
    }];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dishId.count % 3 == 0) {
        return _dishId.count / 3;
    } else {
        return _dishId.count / 3 + 1;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if(cell == nil){
        cell = [[MainTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    } else {
        for (UIView *view in [cell.contentView subviews]) {
            [view removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    if (_imgArray.count % 3 == 0) {
        cell.name1.text = [_nameArray objectAtIndex:(indexPath.row) * 3];
        cell.name2.text = [_nameArray objectAtIndex:(indexPath.row) * 3 + 1];
        cell.name3.text = [_nameArray objectAtIndex:(indexPath.row) * 3 + 2];
        
        [cell.image1 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
        cell.image1.tag = (indexPath.row) * 3;
        [cell.image1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
        
        [cell.image2 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3 + 1] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
        cell.image2.tag = (indexPath.row) * 3 + 1;
        [cell.image2 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
        
        [cell.image3 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3 + 2] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
        cell.image3.tag = (indexPath.row) * 3 + 2;
        [cell.image3 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
    } else if (_imgArray.count % 3 == 1){
        if (indexPath.row == _imgArray.count / 3) {
            cell.name1.text = [_nameArray objectAtIndex:(indexPath.row ) * 3];
            [cell.image1 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image1.tag = (indexPath.row) * 3;
            [cell.image1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            [cell.name2 removeFromSuperview];
            [cell.name3 removeFromSuperview];
        } else {
            cell.name1.text = [_nameArray objectAtIndex:indexPath.row * 3];
            cell.name2.text = [_nameArray objectAtIndex:indexPath.row * 3 + 1];
            cell.name3.text = [_nameArray objectAtIndex:indexPath.row * 3 + 2];
            
            [cell.image1 setImageURLStr:[_imgArray objectAtIndex:indexPath.row * 3] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image1.tag = (indexPath.row) * 3;
            [cell.image1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            
            [cell.image2 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3 + 1] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image2.tag = (indexPath.row) * 3 + 1;
            [cell.image2 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            
            [cell.image3 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3 + 2] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image3.tag = (indexPath.row) * 3 + 2;
            [cell.image3 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
        }
    } else if (_imgArray.count % 3 == 2){
        if (indexPath.row == _imgArray.count / 3) {
            cell.name1.text = [_nameArray objectAtIndex:(indexPath.row ) * 3];
            cell.name2.text = [_nameArray objectAtIndex:(indexPath.row ) * 3 + 1];
            
            [cell.image1 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row ) * 3] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image1.tag = (indexPath.row ) * 3;
            [cell.image1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            
            [cell.image2 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row) * 3 + 1] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image2.tag = (indexPath.row ) * 3 + 1;
            [cell.image2 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            [cell.name3 removeFromSuperview];
        } else {
            cell.name1.text = [_nameArray objectAtIndex:(indexPath.row ) * 3];
            cell.name2.text = [_nameArray objectAtIndex:(indexPath.row ) * 3 + 1];
            cell.name3.text = [_nameArray objectAtIndex:(indexPath.row ) * 3 + 2];
            
            [cell.image1 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row ) * 3] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image1.tag = (indexPath.row ) * 3;
            [cell.image1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            
            [cell.image2 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row ) * 3 + 1] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image2.tag = (indexPath.row ) * 3 + 1;
            [cell.image2 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
            
            [cell.image3 setImageURLStr:[_imgArray objectAtIndex:(indexPath.row ) * 3 + 2] placeholder:[UIImage imageNamed:@"img_delete_advertisement"]];
            cell.image3.tag = (indexPath.row ) * 3 + 2;
            [cell.image3 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonClick:)]];
        }
    }
    return cell;
}
-(void)buttonClick:(UITapGestureRecognizer *)sender {
    [MobClick event:@"clickImage"];
    DetailViewController *detail = [[DetailViewController alloc]init];
    detail.name = [_nameArray objectAtIndex:sender.view.tag];
    detail.bigImg = [_bigImg objectAtIndex:sender.view.tag];
    detail.dishId = [_dishId objectAtIndex:sender.view.tag];
    detail.materialArray = [_materialArray objectAtIndex:sender.view.tag];
    detail.materialQuantity = [_materialQuantity objectAtIndex:sender.view.tag];
    detail.tips = [_tips objectAtIndex:sender.view.tag];
    detail.auxiliaryMaterial = [_auxiliaryMaterial objectAtIndex:sender.view.tag];
    detail.auxiliaryQuantity = [_auxiliaryQuantity objectAtIndex:sender.view.tag];
    detail.introduction = [_introductionArray objectAtIndex:sender.view.tag];
    detail.smallImg = [_imgArray objectAtIndex:sender.view.tag];
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)goTo {
    FavoriteViewController *favor = [[FavoriteViewController alloc]init];
    [self.navigationController pushViewController:favor animated:YES];
}

-(void)clickAdv :(NSInteger)index {
    if (_hotImg.count != 0) {
        DetailViewController *detail = [[DetailViewController alloc]init];
        detail.name = [_hotName objectAtIndex:index];
        detail.bigImg = [_hotBigImg objectAtIndex:index];
        detail.dishId = [_hotId objectAtIndex:index];
        detail.materialArray = [_hotMaterialArray objectAtIndex:index];
        detail.materialQuantity = [_hotMaterialQuantity objectAtIndex:index];
        detail.tips = [_hotTips objectAtIndex:index];
        detail.auxiliaryMaterial = [_hotAuxiliaryMaterial objectAtIndex:index];
        detail.auxiliaryQuantity = [_hotAuxiliaryQuantity objectAtIndex:index];
        detail.introduction = [_hotIntroductionArray objectAtIndex:index];
        detail.smallImg = [_hotImg objectAtIndex:index];
        [self.navigationController pushViewController:detail animated:YES];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
